package global

import (
	"bytes"
	"compress/flate"
	"compress/gzip"
	"fmt"
	"gitee.com/swsk33/sclog"
	"github.com/andybalholm/brotli"
	"io"
	"net/http"
	"time"
)

// httpClient 全局HTTP客户端
var httpClient *http.Client

// AuthHeader 全局认证请求头
var AuthHeader string

func init() {
	httpClient = &http.Client{
		Timeout: 20 * time.Minute,
		Transport: &http.Transport{
			Proxy: http.ProxyFromEnvironment,
		},
	}
}

// 检测返回的请求体是否经过压缩，并返回解压的内容
// response 响应对象
func decodeCompressedBody(response *http.Response) io.Reader {
	encoding := response.Header.Get("Content-Encoding")
	body := response.Body
	var bodyReader io.Reader
	switch encoding {
	case "gzip":
		bodyReader, _ = gzip.NewReader(body)
	case "deflate":
		bodyReader = flate.NewReader(body)
	case "br":
		bodyReader = brotli.NewReader(body)
	default:
		bodyReader = response.Body
	}
	return bodyReader
}

// 创建一个请求对象
//
// urlPath 请求地址路径，以/开头
// method 请求类型
// body 请求体，无请求体传入nil
func createRequest(urlPath, method string, body []byte) (*http.Request, error) {
	// 读取请求体
	var bodyReader io.Reader
	if body != nil {
		bodyReader = bytes.NewReader(body)
	}
	// 创建请求
	request, e := http.NewRequest(method, fmt.Sprintf("https://m2m.cr.usgs.gov/api/api/json/stable%s", urlPath), bodyReader)
	if e != nil {
		sclog.ErrorLine("创建请求出错！")
		return nil, e
	}
	// 设定请求头
	request.Header.Add("X-Auth-Token", AuthHeader)
	return request, nil
}

// SendRequest 发送HTTP请求
//
// urlPath 请求地址路径，以/开头
//
// method 请求类型
//
// body 请求体，无请求体传入nil
func SendRequest(urlPath, method string, body []byte) ([]byte, error) {
	// 准备请求
	request, e := createRequest(urlPath, method, body)
	if e != nil {
		return nil, e
	}
	// 发请求
	response, e := httpClient.Do(request)
	if e != nil {
		sclog.ErrorLine("发送请求出错！")
		return nil, e
	}
	defer func() {
		_ = response.Body.Close()
	}()
	// 解析响应体
	bodyReader := decodeCompressedBody(response)
	result, e := io.ReadAll(bodyReader)
	if e != nil {
		sclog.ErrorLine("读取响应体出错！")
		return nil, e
	}
	return result, nil
}